package cn.kwq.project_manger.service.impl;

import cn.kwq.project_manger.pojo.QProject;
import cn.kwq.project_manger.pojo.QTeam;
import cn.kwq.project_manger.pojo.QTeamProject;
import cn.kwq.project_manger.pojo.TeamProject;
import cn.kwq.project_manger.repostitory.TeamProjectRepository;
import cn.kwq.project_manger.service.TeamProjectService;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;

@Service
@Slf4j
public class TeamProjectServiceImpl implements TeamProjectService {

    @Autowired
    TeamProjectRepository teamProjectRepository;
    @Autowired
    JPAQueryFactory jpaQueryFactory;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean teamBindProject(Long teamId, Long projectId) {
        QTeamProject teamProject=QTeamProject.teamProject;
        TeamProject teamProject1 = jpaQueryFactory.selectFrom(teamProject)
                .where(teamProject.projectId.eq(projectId))
                .where(teamProject.teamId.eq(teamId))
                .fetchOne();
        if (teamProject1!=null){
            throw new RuntimeException("本队伍已绑定项目");
        }

        TeamProject one = teamProjectRepository.save(TeamProject
                .builder()
                .projectId(projectId)
                .teamId(teamId)
                .build());

        Optional<TeamProject> save = teamProjectRepository.findById(one.getTeamProjectId());


        AtomicBoolean saveSuccess= new AtomicBoolean(false);

        save.ifPresent(item->{
            if (save.get().getProjectId()==null){
                saveSuccess.compareAndSet(false,false);
            }
            else  if (save.get().getTeamId()==null){
                saveSuccess.compareAndSet(false,false);
            }else {
                saveSuccess.compareAndSet(false,true);
            }
        });
        if (!saveSuccess.get()){
            throw new RuntimeException("绑定失败");
        }else {
            //更新队伍项目名字
            QProject project=QProject.project;
            String projectName = jpaQueryFactory.select(project.projectName)
                    .from(project)
                    .where(project.projectId.eq(projectId))
                    .fetchOne();

            Optional.ofNullable(projectName).ifPresent(pn->{
                log.info(projectName+"绑定到"+teamId+"队伍");
                QTeam team=QTeam.team;
                jpaQueryFactory.update(team)
                        .set(team.teamProjectName,pn)
                        .where(team.teamId.eq(teamId))
                        .execute();
            });

        }
        return saveSuccess.get();
    }
}
